local lfs = require 'lfs'
local unity = require 'luaUnity'
local mpi = require "luaMPI"
local nl = require"luaNumeric"
--require "Q3DViewer"
-- require "luaQt"

----------------------------------------------------------------------------------------------------------------------------------------
--初始化参数
local ParaSweep={
	solvers={"FDTD","RCWA","RCWABeam","RCWABeam2D","SBRApp"};
	index = "FDTD";
	solvers_impl = {FDTD=Gallop.Solver, RCWA=Gallop.RCWASolver, RCWABeam=Gallop.RCWABeamSolver, RCWABeam2D=Gallop.RCWABeam2DSolver , SBRApp=Gallop.SBRApp};
	export_gif = false;
	is_save_models = false;
	
	--solvers_settings = { FDTD=[[ abc ]]; };
	pre_settings = {
		FDTD=[[
-----------------------------------------------------------------------
--参数扫描前处理函数
function prerun(self)
	self:clearGraphs()
end
-----------------------------------------------------------------------
]];
	RCWA=[[
-----------------------------------------------------------------------
--参数扫描前处理函数
function prerun(self)
	Geometry.RCWASolver.refView = self.resultsView
	self:clearGraphs()
	Geometry.RCWASolver:init_plot();
end
-----------------------------------------------------------------------
]];

	RCWABeam=[[
-----------------------------------------------------------------------
--参数扫描前处理函数
function prerun(self)
	Geometry.RCWABeamSolver.farFieldsView = self.resultsView
	self:clearGraphs()
end
-----------------------------------------------------------------------
	]];
	
	RCWABeam2D=[[
-----------------------------------------------------------------------
--参数扫描前处理函数
function prerun(self)
	--Geometry.RCWABeam2DSolver.refView = self.resultsView
	self:clearGraphs()
end
-----------------------------------------------------------------------
	]];
	
	SBRApp=[[
-----------------------------------------------------------------------
--参数扫描前处理函数
function prerun(self)
	Gallop.SBRApp:initSolver();
end
-----------------------------------------------------------------------
	]];
};

	solvers_settings = {
	FDTD=[[
-----------------------------------------------------------------------
--每一步扫描过程执行函数
function step(self,idx)

	--保存当前视图
	--self.view3D:saveSnapShot("view"..idx..".png")

	--求解
	Gallop.Solver:runSolver();

	
	--Geometry.RCWASolver:add_data_to_plot("TM", 0, 0,false,true,tostring(idx));

end	
-----------------------------------------------------------------------
	]];
	RCWA=[[

-----------------------------------------------------------------------
--每一步扫描过程执行函数
function step(self,idx)

	--保存当前视图
	--self.view3D:saveSnapShot("view"..idx..".png")
	
	--根据当前几何模型，建立RCWA
	--如果几何结构没有更新，或者手动更新，可以注释掉这一行代码
	Geometry.RCWASolver:create_model_from_gui()

	--求解RCWA模型
	Geometry.RCWASolver:solve();
	
	
	--Geometry.RCWASolver:add_data_to_plot("TM", 0, 0,false,true,'[idx='..tostring(idx)..']');
	
	--添加数据到视图
	Geometry.RCWASolver:add_data_to_viewer({
				viewer=self.resultsView;
				polar = "TE";
				order = {0,0};
				port = "ref"; -- or "tran"
				type = "abs"; -- "abs" or "phs" , 分别对应效率和相位
				--xaxis = "angle"; -- or "lambda" ,  分别对于角度谱和频谱
				lable = '[idx='..tostring(idx)..']'
	}
	)

end	
-----------------------------------------------------------------------

	]];
	
		RCWABeam=[[
-----------------------------------------------------------------------
--每一步扫描过程执行函数
function step(self,idx)

	--保存当前视图
	--self.view3D:saveSnapShot("view"..idx..".png")
	
	--根据当前几何模型，建立RCWA
	--如果几何结构没有更新，或者手动更新，可以注释掉这一行代码
	Geometry.RCWABeamSolver:create_model_from_gui()

	--求解RCWA模型
	Geometry.RCWABeamSolver:solve();
	
	
	Geometry.RCWABeamSolver:add_farfield_plot();

end	
-----------------------------------------------------------------------
	]];
	
			RCWABeam2D=[[
-----------------------------------------------------------------------
--每一步扫描过程执行函数
function step(self,idx)

	--保存当前视图
	--self.view3D:saveSnapShot("view"..idx..".png")
	
	--根据当前几何模型，建立RCWA
	--如果几何结构没有更新，或者手动更新，可以注释掉这一行代码
	Geometry.RCWABeam2DSolver:create_model_from_gui()

	--求解RCWA模型
	Geometry.RCWABeam2DSolver:solve();
	
	
	--Geometry.RCWABeam2DSolver:add_data_to_plot("TM", 0, 0,false,true,tostring(idx));

end	
-----------------------------------------------------------------------

	]];
	
		SBRApp=[[
-----------------------------------------------------------------------
--每一步扫描过程执行函数
function step(self,idx)
	Gallop.SBRApp:preRunSolver(idx);

	--求解
	Gallop.SBRApp:runSolver();
	
	Gallop.SBRApp:postRunSolver(idx);
end	
-----------------------------------------------------------------------
	]];
	};

	post_settings = {
	FDTD=[[
-----------------------------------------------------------------------
--参数扫描后处理函数
function postrun(self)
end
-----------------------------------------------------------------------
	]];
	RCWA=[[
-----------------------------------------------------------------------
--参数扫描后处理函数
function postrun(self)
end
-----------------------------------------------------------------------
	]];
	
	RCWABeam=[[
-----------------------------------------------------------------------
--参数扫描后处理函数
function postrun(self)
end
-----------------------------------------------------------------------
]];
	
	RCWABeam2D=[[
-----------------------------------------------------------------------
--参数扫描后处理函数
function postrun(self)
end
-----------------------------------------------------------------------
	]];
	
	SBRApp=[[
-----------------------------------------------------------------------
--参数扫描后处理函数
function postrun(self)
end
-----------------------------------------------------------------------
	]];
	};
	
	set_settings_str = Gallop.set_settings_str;
	get_settings_str = Gallop.get_settings_str;
	
	runned_index = nl.new_ivector();
};
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--创建表和创建元表
function ParaSweep:new (o)
	print( 'Init Parameter Module' )
	o = o or {};
	self.__index = self;
	setmetatable(o,self)
	o:regist_funcs_to_gallop();
 	o.init_strs = o:get_settings_str();
	return o;
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--注册全局函数
function ParaSweep:get_settings_str()
	local str = Gallop.get_settings_str(self);
	str = str .. 'pre_settings='..dump_t( self.pre_settings )..'\n';
	str = str .. 'solvers_settings='..dump_t( self.solvers_settings )..'\n';
	str = str .. 'post_settings='..dump_t( self.post_settings )..'\n';
	--str = str .. 'pre_settings=[['..dump_t( self.pre_settings )..']];';
	return str;
end
----------------------------------------------------------------------------------------------------------------------------------------


----------------------------------------------------------------------------------------------------------------------------------------
--注册全局函数
function ParaSweep:regist_funcs_to_gallop()
	Gallop.init_funcs['ParametersSweep'] = function()
		local str = self.init_strs;
		assert( type('str')=='string', 'Parameters Sweep init string error' );
		if str ~= '' then
			--print(str)
			Gallop.ParametersSweep:set_settings_str(str)
		end
		self:init_ui();
	end;
	Gallop.load_funcs['ParametersSweep'] = function()	
		local str = Geometry.get_setting( 'ParametersSweep.Settings' )
		Gallop.ParametersSweep:set_settings_str(str);
		local idx = Geometry.get_setting( 'ParametersSweep.SolverIndex');
		if idx~='' then self.index = idx end;
		self:init_ui();		
	end;	
	Gallop.presave_funcs['ParametersSweep'] = function()
		self:update_settings_from_ui();
		self:update_script_settings_from_ui();
		Geometry.set_setting( 'ParametersSweep.SolverIndex', self.index);
		local str = Gallop.ParametersSweep:get_settings_str();
		Geometry.set_setting( 'ParametersSweep.Settings', str );
	end;	
end
----------------------------------------------------------------------------------------------------------------------------------------



----------------------------------------------------------------------------------------------------------------------------------------
--更新求解器列表
function ParaSweep:update_solver_list_to_ui ()
end
function ParaSweep:update_settings_to_ui ()
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--更新求解器列表，具体函数由GUI提供的函数覆盖
function ParaSweep:update_solver_settings_to_ui ()
end
function ParaSweep:update_solver_settings_from_ui ()
end
function ParaSweep:update_pre_settings_to_ui ()
end
function ParaSweep:update_pre_settings_from_ui ()
end
function ParaSweep:update_post_settings_to_ui ()
end
function ParaSweep:update_post_settings_from_ui ()
end
function ParaSweep:update_settings_from_ui ()
end
function ParaSweep:update_script_settings_to_ui ()
	self:update_solver_settings_to_ui();
	self:update_pre_settings_to_ui();
	self:update_post_settings_to_ui();
end
function ParaSweep:update_script_settings_from_ui ()
	self:update_solver_settings_from_ui();
	self:update_pre_settings_from_ui();
	self:update_post_settings_from_ui();
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--更新求解器进度条，具体函数由GUI提供的函数覆盖
function ParaSweep:update_progress_bar (p)
end
function ParaSweep:update_runned_state (ivector)
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--更新参数到GUI界面
function ParaSweep:init_ui ()
	self:update_solver_list_to_ui()
        self:update_script_settings_to_ui()
        self:update_settings_to_ui()
        self:init_functions();
end
----------------------------------------------------------------------------------------------------------------------------------------


----------------------------------------------------------------------------------------------------------------------------------------
--设置求解器类型
function ParaSweep:change_solver_index (idx)
	if idx ~= self.index then
		self:update_script_settings_from_ui();
		self.index = idx;
		self:update_solver_list_to_ui();
		self:update_script_settings_to_ui();
		self.need_init = true;
	end
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--获得求解器类型，输入类型为Map，由GUI调用
 function ParaSweep:get_settings (set)
	 set:clear();	
	 --print("Get Settings Map")
	 for k,v in pairs(self.solvers_settings) do
		 -- print(k,v)
		 set:insert(k,v);
	 end
 end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--设置求解器参数
function ParaSweep:set_settings (set)
	for k,v in pairs(set) do
		self.solvers_settings[k]=v;
	end
	self:init_ui()
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--设置求解器
function ParaSweep:set_solver_settings (settings)
	if self.solvers_settings[self.index] ~= settings then
		self.solvers_settings[self.index] = settings;
		self.need_init = true;
	end
	self:update_solver_settings_to_ui();
	self:init_functions();
end
function ParaSweep:set_pre_settings (settings)
	self.pre_settings[self.index] = settings;
	self:update_pre_settings_to_ui();
	self:init_functions();
end
function ParaSweep:set_post_settings (settings)
	self.post_settings[self.index] = settings;
	self:update_post_settings_to_ui();
	self:init_functions();
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--获取求解器设置
function ParaSweep:get_solver_settings ()
	settings = self.solvers_settings[self.index] or '';
	return settings;
end
function ParaSweep:get_pre_settings ()
	settings = self.pre_settings[self.index] or '';
	return settings;
end
function ParaSweep:get_post_settings ()
	settings = self.post_settings[self.index] or '';
	return settings;
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--检查参数按钮所触发的函数
function ParaSweep:check_parameters ()
    
    --if self.console~=true then
     	--local gallop = require"QGMainWindow"
	--local mw = gallop.getMainWindow();
	--self.view3D = mw:get3DView() 
     --end	
     self.view3D = Gallop.View:get3DView()
	self:update_settings_from_ui();

	self:update_script_settings_from_ui();

	--self.names,self.paraList = Gallop.Parameters.get_sweep_list()
	local names, paraList = Gallop.Parameters.get_sweep_list()

	-- self:update_solver_settings_to_ui();
	
	self:update_solver_list_to_ui();
	
	if self.export_gif then
		print( unity.get_full_path('./.sweep') );
		unity.remove('./.sweep');
		unity.mkdir('./.sweep')
	end
			
	for k,v in pairs( paraList ) do
		Gallop.Parameters.update_sweep_list_to_variables(k)
		Gallop.Parameters.valuate()
		if self.export_gif then
			self.view3D:saveSnapShot(string.format("./.sweep/sweep%05d.png",k))
		end
	end
	
	if self.export_gif then
		os.execute( 'magick -loop 0 -delay 10 ./.sweep/*.png a.gif' )
	end
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--初始化函数
function ParaSweep:init_functions ()
     local f = load(self.pre_settings[self.index])
     f();    
     assert( type(prerun) == "function", 'prerun function not defined')
     self.prerun = prerun;   
     
     local f = load(self.post_settings[self.index])
     f();  
     assert( type(postrun) == "function", 'postrun function not defined')
     self.postrun = postrun;
     
     --print( 'init solver' )
     local f = load(self.solvers_settings[self.index])
     f();     
     assert( type(step) == "function", 'step function not defined')
     self.step = step;
      
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--初始化求解器
function ParaSweep:init_path ()
     self.proPath = Geometry.get_project_path_utf8();
     self.stemPath = Geometry.get_project_stem_utf8();
     self.proName = Geometry.get_project_name_utf8();
     self.modelsPath = self.stemPath ..'-SweepModels/';	
     self.probesPath = self.stemPath ..'-Probes/';	
     --unity.remove(self.modelsPath)
     if self.proName ~= '' then	
	unity.remove(self.modelsPath)
	unity.mkdir(self.modelsPath)
	unity.remove(self.probesPath)
	unity.mkdir(self.probesPath)
     end
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--参数设置
function ParaSweep:change_save_models(s)
	assert( type(s)=='boolean' , '参数类型出错')
	self.is_save_models = s;
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--初始化求解器
function ParaSweep:init_solver ()

---[[	
     if Gallop.View.console~=true then
     	local gallop = require"QGMainWindow"
	local mw = gallop.getMainWindow();
	self.view3D = mw:get3DView() 
     end
--]]	
     self:update_script_settings_from_ui();
     
     self:update_settings_from_ui();
     
     self:init_functions();
     
     if self.data == nil then self.data = {} end;
     
     self.names,self.paraList = Gallop.Parameters.get_sweep_list()	
     self.paraIndex = Gallop.Parameters.get_sweep_index();

	self:init_path();

     if self.need_init  == false then
	return;
     end

          
     self:clear_all_results()
     self.need_init = false;
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--设置指定系数的参数已经完成扫描
function ParaSweep:set_run (k)
	if #self.paraList ~= #self.runned_index then
		self.runned_index = nl.new_ivector( #self.paraList );
		for k,v in pairs(self.runned_index) do
			self.runned_index[k] = 0;
		end
	end
	self.runned_index[k] = 1;
	self:update_runned_state(self.runned_index);
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--保存和读取数据
--function ParaSweep:save_probes (k)
	--self.data[k] = {};
	--self.data[k].pbs = {};
	--local pbs = Geometry.objects("probes");
	--for kk,vv in pairs( pbs ) do 
		--self.data[k].pbs[kk] = vv:copy();
	--end
--end
--function ParaSweep:retrive_probes (k)
	--if self.data == nil then
		--self.data = {};
	--end
	--if self.data[k] == nil then
		--self.data[k] = {};
	--end
	--if self.data[k].pbs ~= nil then
		--Geometry.RemoveProbes();
		--for kk,vv in pairs (self.data[k].pbs) do
			--Geometry.AddProbe( vv )
		--end
	--end	
--end


--===============================================================--
--保存所有探测器，保存探测器计算结果到硬盘
function ParaSweep:save_probes (k)
	self.data[k] = {};
	self.data[k] = self.solvers_impl[ self.index ]:getResults(k);	
	if  self.solvers_impl[ self.index ].saveResults2Path ~= nil  then
		self.solvers_impl[ self.index ]:saveResults2Path(self.probesPath, self.currModelName)
	end
end
--===============================================================--

function ParaSweep:retrive_probes (k)
	if self.data == nil then
		self.data = {};
	end
	if self.data[k] == nil then
		self.data[k] = {};
	end
	if #self.data[k] > 0  then
		self.solvers_impl[ self.index ]:setResults(self.data[k],k);	
	end
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--保存和读取models
function ParaSweep:save_current_model(k)	
	--print('modelsPath:',self.modelsPath)
	Geometry.SaveGeometry( self.modelsPath .. self.currModelName .. '.gap');
	Geometry.save_summary(self.modelsPath .. self.currModelName .. '-runinfo.log')
	print('proPath:',self.proPath)
	Geometry.set_path( self.proPath );
end
----------------------------------------------------------------------------------------------------------------------------------------


--------------------------------------------------------------------------------------------------------------------------------------
--保存和读取probes
--function ParaSweep:save_current_model_probes (k)	
	--Geometry.SaveGeometry( self.modelsPath .. '/' .. self.currModelName .. '.gap');
	--Geometry.set_path( self.proPath );
--end
--------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--指定系数的参数是否已经完成扫描
function ParaSweep:is_run (k)
	if #self.paraList ~= #self.runned_index then
		return false;
	end
	--print( self.runned_index:size(), k )
	local sta = self.runned_index[k];
	--print( 'sta=' , sta );
	return sta == 1;
	
	--return self.runned_index[k] == 1;
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--清除所有计算数据
function ParaSweep:clear_all_results()
	--print('clear')
	self:init_path()
	
	if self.proName ~= '' then
		unity.remove(self.modelsPath)
		unity.mkdir(self.modelsPath)
	end
	self.data = nil;
	self.runned_index = nl.new_ivector();
	self:update_runned_state(self.runned_index);
	self:update_progress_bar(0);
end
----------------------------------------------------------------------------------------------------------------------------------------


----------------------------------------------------------------------------------------------------------------------------------------
--清除所有图像
function ParaSweep:clearGraphs ()
	if self.resultsView then
		self.resultsView:clearGraphs()
	end
end

function ParaSweep:clear_all_graphs()
	if self.console~=true then
		self.resultsView:clearGraphs()
	end
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--清除所有计算数据
function ParaSweep:clear_models (idx)
	--print('clear')
	if self.paraList == nil or self.runned_index == nil then
		return
	end
	if #self.paraList ~= #self.runned_index then
		self.runned_index = nl.new_ivector( #self.paraList );
		for k,v in pairs(self.runned_index) do
			self.runned_index[k] = 0;
			self.data[k] = nil;
		end
	end
	for k,v in pairs (idx) do
		self.runned_index[v] = 0;
	end
	self:update_runned_state(self.runned_index);
	self:update_progress_bar(0);
end
----------------------------------------------------------------------------------------------------------------------------------------


----------------------------------------------------------------------------------------------------------------------------------------
--计算models的路径字符串
function ParaSweep:get_curr_model_name (k)	
	local str = self.proName;
	for kk,vv in pairs( self.names ) do 
		str = str .. '-' ..vv .. '(';
		str = str .. self.paraList[k][kk];
		str = str .. ')';
	end
	self.currModelName  = str;
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--更新参数到模型
function ParaSweep:update_parameters_to_model (k)

	--print( 'update parameters,idx = ' .. k );
	--self.names,self.paraList = Gallop.Parameters.get_sweep_list()
	
	local names, paraList = Gallop.Parameters.get_sweep_list()


	assert( k <= #paraList, 'index out of range: index[' .. k .. '] larger than size of parameters list['.. #paraList ..']');
	
	Gallop.Parameters.update_sweep_list_to_variables(k)
	
	--print( 'valuate ..' );
	Gallop.Parameters.valuate()
	--if self.console~=true then
		--self.view3D:refresh()
	--end
	--print( 'retrive data' );
	self:retrive_probes(k)

	--print( 'refresh view' );
	Gallop.View:refresh_view3D();
	
	self:get_curr_model_name(k);
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--求解指定的参数
function ParaSweep:run_models (idx)
	print( "init solver... ")
	self:init_solver();
	
	print( "prerun... ")	
	self:prerun();	
	
	for k,v in pairs( self.runned_index ) do 
		if v==1 then self:retrive_probes(k) end;
	end
	
	--local names, paraList = Gallop.Parameters.get_sweep_list()

	local num = #idx;
	
	print( "run models... ")	
	for k,v in pairs( idx ) do
		if self:is_run( v ) == false then
			self:update_parameters_to_model(v)
			self:step(v);			
			self:update_progress_bar( k / num *100 );
			self:set_run(v);
			self:save_probes(v)
		end
	end
	
	self:update_progress_bar( 100 );
	
	print( "postrun... ")	
	self:postrun();

end
----------------------------------------------------------------------------------------------------------------------------------------



----------------------------------------------------------------------------------------------------------------------------------------
--求解器求解
function ParaSweep:run_sweep ()
	self:init_solver();
	
	self:prerun();	
	
	--self.names, self.paraList = Gallop.Parameters.get_sweep_list()
	local names, paraList = Gallop.Parameters.get_sweep_list()
	
	--print( "Paramters List :" .. #paraList , "start ...")	


	for k,v in pairs( paraList ) do
		--print( 'sweep start, idx : ', k )
		if self:is_run( k ) == false then
			--print( "run idx:".. k, v )
			self:update_parameters_to_model(k)
			self:step(k);			
			self:update_progress_bar( k / #self.paraList *100 );
			self:set_run(k);
			self:save_probes(k)
			
			--保存当前模型到硬盘
			if self.is_save_models == true then 
				self:save_current_model(k);
			end
		else
			self:retrive_probes(k)
		end
		--print( 'sweep finished, idx : ', k )
	end
	
	self:update_progress_bar( 100 );

	self:postrun();

end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--并行求解
function ParaSweep:run_sweep_mpi ()
	self:init_solver();	
	
	self:prerun();	

	--self.names, self.values = Gallop.Parameters.get_sweep_list()
	local names, paraList = Gallop.Parameters.get_sweep_list()

	self:update_progress_bar( 0 );
	
	for k,v in pairs( paraList ) do
		if id_groups==(k-1)%num_groups then
			print( "run idx:".. k, v )
			
			self:update_parameters_to_model(k)
			self:step(k);			
			self:update_progress_bar( k / #self.paraList *100 );
			self:set_run(k);
			self:save_probes(k)
			
			--保存当前模型到硬盘
			if self.is_save_models == true then 
				self:save_current_model(k);
			end
		end
	end
	
	self:update_progress_bar( 100 );

	self:postrun();
end
----------------------------------------------------------------------------------------------------------------------------------------




function ParaSweep:add_viewer()
	if self.console~=true then
		-- local mw = require "QGMainWindow"
		-- local mm = mw.getMainWindow();
		-- self.view = mm:get3DView() 		
		local gallop = require "QGMainWindow"
		self.mw = gallop.getMainWindow();
		self.resultsView = self.mw:create2DView("View2D");
	end
end

function ParaSweep:select_native_view()
	if self.console~=true then
		self:get_native_viewer()
	end
end

function ParaSweep:select_active_view()
	if self.console~=true then
		local gallop = require"QGMainWindow"
		self.mw = gallop.getMainWindow();
		local view = self.mw:activeViewer2DChild();
		assert(self.mw:hasView(view)==true,"The active view is not a 2D viewer!")
		self.resultsView = view;
	end
end

return ParaSweep;



